# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jaewon

import hashlib

from tornado import gen
from urllib.parse import urlencode
from coin.exchange.base.order_gateway import OrderSide
from coin.exchange.util.async_http_client import AsyncHttpClient


class OkexRestTrade(object):
  def __init__(self,
               api_key,
               secret_key,
               timeout=15,
               *,
               order_timeout=15,
               http_client=None,
               max_connections=6):
    self._api_key = api_key
    self._secret_key = secret_key
    self._order_timeout = order_timeout
    self._timeout = timeout
    self._http_client = http_client or AsyncHttpClient(max_connections=max_connections)

  def _sign(self, param: dict):
    req_param = []
    for key in sorted(param.keys()):
      req_param.append('%s=%s' % (str(key), str(param[key])))
    req_param.append('secret_key=%s' % self._secret_key)
    req_str = '&'.join(req_param)
    return hashlib.md5(req_str.encode('utf-8')).hexdigest().upper()

  def ticker(self, symbol):
    response = self._http_client.get('https://www.okex.com/api/v1/ticker.do?symbol=%s' % symbol,
                                     timeout=self._timeout)
    return response

  @gen.coroutine
  def userinfo(self):
    param = {'api_key': self._api_key}
    param['sign'] = self._sign(param)
    body = urlencode(param)
    response = yield self._http_client.post(
        'https://www.okex.com/api/v1/userinfo.do',
        method='POST',
        headers={'Content-Type': 'application/x-www-form-urlencoded'},
        data=body,
        timeout=self._timeout)
    return response

  @gen.coroutine
  def order(self, symbol: str, order_side: OrderSide, price: float, qty: float):
    if order_side == OrderSide.BUY:
      okex_order_type = 'buy'
    elif order_side == OrderSide.SELL:
      okex_order_type = 'sell'
    else:
      raise ValueError()

    param = {
        'api_key': self._api_key,
        'symbol': symbol,
        'price': '%.8f' % price,
        'amount': '%.8f' % qty,
        'type': okex_order_type
    }
    param['sign'] = self._sign(param)
    body = urlencode(param)
    response = yield self._http_client.post(
        'https://www.okex.com/api/v1/trade.do',
        headers={'Content-Type': 'application/x-www-form-urlencoded'},
        data=body,
        timeout=self._order_timeout)
    return response

  @gen.coroutine
  def order_history(self, symbol, working_order=True):
    param = {
        'api_key': self._api_key,
        'symbol': symbol,
        'status': 0 if working_order else 1,
        'current_page': 1,
        'page_length': 200
    }
    param['sign'] = self._sign(param)
    body = urlencode(param)
    response = yield self._http_client.post(
        'https://www.okex.com/api/v1/order_history.do',
        headers={'Content-Type': 'application/x-www-form-urlencoded'},
        data=body,
        timeout=self._timeout)
    return response
